/**
 * WebSocket 工具类
 * 用于管理用户端的 WebSocket 连接
 */

export class UserWebSocket {
  constructor(userId, userName) {
    this.userId = userId
    this.userName = userName || '用户'
    this.serviceId = '1001' // 默认客服ID
    this.ws = null
    this.onMessage = null
    this.onError = null
    this.onClose = null
    this.onOpen = null
    this.reconnectTimer = null
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.shouldReconnect = true // 是否允许自动重连，默认允许
  }

  /**
   * 连接到 WebSocket 服务器
   */
  connect() {
    // 构建 WebSocket URL，包含用户名参数
    const userNameEncoded = encodeURIComponent(this.userName)
    const wsUrl = `ws://127.0.0.1:8000/ws/${this.userId}?client_name=${userNameEncoded}`
    
    try {
      this.ws = new WebSocket(wsUrl)

      this.ws.onopen = () => {
        console.log('用户 WebSocket 连接成功')
        this.reconnectAttempts = 0
        this.shouldReconnect = true // 连接成功后重置重连标志
        if (this.reconnectTimer) {
          clearTimeout(this.reconnectTimer)
          this.reconnectTimer = null
        }
        if (this.onOpen) {
          this.onOpen()
        }
      }

      this.ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data)
          
          // 忽略状态消息（sent, failed）
          if (data.status) {
            return
          }
          
          // 处理收到的消息
          if (this.onMessage) {
            this.onMessage(data)
          }
        } catch (error) {
          console.error('解析 WebSocket 消息失败:', error)
        }
      }

      this.ws.onerror = (error) => {
        console.error('WebSocket 错误:', error)
        if (this.onError) {
          this.onError(error)
        }
      }

      this.ws.onclose = () => {
        console.log('WebSocket 连接已关闭')
        if (this.onClose) {
          this.onClose()
        }
        // 只有在允许重连的情况下才自动重连
        if (this.shouldReconnect) {
          this.reconnect()
        } else {
          console.log('WebSocket 连接已主动关闭，不进行自动重连')
          // 重置重连标志，以便下次连接时可以重连
          this.shouldReconnect = true
        }
      }
    } catch (error) {
      console.error('创建 WebSocket 连接失败:', error)
      if (this.onError) {
        this.onError(error)
      }
    }
  }

  /**
   * 自动重连
   */
  reconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('达到最大重连次数，停止重连')
      return
    }

    this.reconnectAttempts++
    const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000) // 指数退避，最大30秒
    
    console.log(`${delay}ms 后尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`)
    
    this.reconnectTimer = setTimeout(() => {
      this.connect()
    }, delay)
  }

  /**
   * 发送消息给客服
   */
  sendMessage(message, extraData = {}) {
    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
      console.error('WebSocket 未连接')
      return false
    }

    const messageData = {
      from: this.userId,
      to: `service${this.serviceId}`,
      message: message,
      timestamp: new Date().toISOString(),
      ...extraData
    }

    try {
      this.ws.send(JSON.stringify(messageData))
      return true
    } catch (error) {
      console.error('发送消息失败:', error)
      return false
    }
  }

  /**
   * 断开连接
   * @param {boolean} disableReconnect - 是否禁用自动重连，默认为 true（主动断开时不重连）
   */
  disconnect(disableReconnect = true) {
    // 如果禁用重连，设置标志
    if (disableReconnect) {
      this.shouldReconnect = false
    }
    
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer)
      this.reconnectTimer = null
    }
    
    if (this.ws) {
      this.ws.close(1000, '主动断开')
      this.ws = null
    }
  }

  /**
   * 检查连接状态
   */
  isConnected() {
    return this.ws && this.ws.readyState === WebSocket.OPEN
  }
}

